<template>
  <el-form
      ref="newsFormRef"
      :model="newsForm"
      :rules="rules"
      label-width="120px"
      class="demo-newsForm"
      :size="formSize"
      status-icon
  >

    <el-form-item label="库存" prop="name" placeholder="请输入新闻标题">
      <el-input v-model="newsForm.name" />
    </el-form-item>

    <el-form-item label="名称" prop="text" >
      <el-input v-model="newsForm.text" />
    </el-form-item>

    <el-form-item label="创建时间" prop="createTime" required>
      <el-date-picker
          v-model="newsForm.createTime"
          type="date"
          label="Pick a date"
          placeholder="Pick a date"
          style="width: 100%"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(newsFormRef)">
        创建
      </el-button>
      <el-button @click="resetForm(newsFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {NewsForm,NewsImpl} from "@/type/NewsAction";
import {addNews} from "@/request/NewsService";

// ref 单个 变量 响应 对象
const formSize = ref('default')
const newsFormRef = ref<FormInstance>()
// 多个变量reactive 响应
const  newsForm = reactive(new NewsImpl()).newsform

const rules = reactive<FormRules<NewsForm>>({
  name: [
    { required: true, message: 'Please input news name', trigger: 'blur' },
    { min: 0, max: 10, message: 'Length should be 0 to 10', trigger: 'blur' },
  ],
  //图片
  text: [
    { required: true, message: 'Please input news text', trigger: 'blur' },
    { min: 0, max: 10, message: 'Length should be 0 to 10', trigger: 'blur' },
  ],
  createTime: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //提交 局部刷新 then() 返回成功的时候调用
      newsForm.createTime=JSON.stringify(newsForm.createTime).substring(1,20).replace("T"," ");
      addNews(newsForm).then(
          function(response) {
            console.log(response);
            //response.data ==== 后台返回的对象 CommentReslut
            console.log("response.data = "+response.data);
            console.log("response.data.message = "+response.data.message);
            console.log("response.data.data = "+response.data.data);
          }
      )
      console.log('提交成功!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>

<style scoped>

</style>
